package com.ptmall.app.net.http;

import android.text.TextUtils;
import android.util.Log;


import org.json.JSONObject;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by Administrator on 2018/3/27.
 */

public class NetworkResponseInterceptor implements Interceptor {

    private final String TAG = "xuccNetworkResponse";

    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        boolean logBody = true;
        boolean logHeaders = true;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }

        /* header test start */
//        if (logHeaders) {
//            if (hasRequestBody) {
//                // Request body headers are only present when installed as a network interceptor. Force
//                // them to be included (when available) so there values are known.
//                if (requestBody.contentType() != null) {
//                    Log.d(TAG, "Content-Type: " + requestBody.contentType());
//                    Log.d(TAG, "requestBody.toString: " + requestBody.toString());
//                }
//                if (requestBody.contentLength() != -1) {
//                    Log.d(TAG, "Content-Length: " + requestBody.contentLength());
//                }
//            }
//
//            Headers headers = request.headers();
//            for (int i = 0, count = headers.size(); i < count; i++) {
//                String name = headers.name(i);
//                // Skip headers from the request body as they are explicitly logged above.
//                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
//                    Log.d(TAG, name + ": " + headers.value(i));
//                }
//            }
//
//            if (!logBody || !hasRequestBody) {
//                Log.d(TAG,"--> END " + request.method());
//            } else if (bodyEncoded(request.headers())) {
//                Log.d(TAG,"--> END " + request.method() + " (encoded body omitted)");
//            } else {
//                Buffer buffer = new Buffer();
//                requestBody.writeTo(buffer);
//
//                Charset charset = UTF8;
//                MediaType contentType = requestBody.contentType();
//                if (contentType != null) {
//                    charset = contentType.charset(UTF8);
//                }
//
//                Log.d(TAG,"");
//                if (isPlaintext(buffer)) {
//                    Log.d(TAG,buffer.readString(charset));
//                    Log.d(TAG,"--> END " + request.method()
//                            + " (" + requestBody.contentLength() + "-byte body)");
//                } else {
//                    Log.d(TAG,"--> END " + request.method() + " (binary "
//                            + requestBody.contentLength() + "-byte body omitted)");
//                }
//            }
//        }
        /* header test end */



        String arg = "";
        if (logHeaders && null != requestBody) {

                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                if (isPlaintext(buffer)) {
                    arg = buffer.readString(charset);
//                    Log.d("xuccNetworkResponse", buffer.readString(charset));
                }
        }

        //开始时间
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            throw e;
        }
        //花费时间
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        String url = response.request().url()+"";

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";

        if (logHeaders) {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    try {
                        charset = contentType.charset(UTF8);
                    } catch (UnsupportedCharsetException e) {
                        return response;
                    }
                }

                if (!isPlaintext(buffer)) {
                    return response;
                }
                if (contentLength != 0) {
                    String body = buffer.clone().readString(charset);
                    if (!TextUtils.isEmpty(body)) {
                        try {
                            JSONObject object = new JSONObject(body);
                            Log.i("xucc",body);
                            String info = null;
                            if (null != object) {
                                info = object.getString("msg");
                            }
                            if (!TextUtils.isEmpty(info)) {
//                                OtherDeviceLoginCheck.check(info);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
//                    Log.d(TAG, "BuildConfig.DEBUG="+BuildConfig.DEBUG);
//                    Log.d(TAG, "BuildConfig.DEBUG="+ BuildConfig.DEBUG);
//                    Log.d(TAG, "BuildConfig.HOST="+ SpUtil.getHostApi());
                    //if (BuildConfig.DEBUG) {
                        Log.d(TAG, "url="+url+"\narg="+arg+"\ntookMs="+tookMs+"ms\nrespones="+body);
                    //}
                }
        }

        return response;
    }


    static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
